# --coding:utf-8--
import httpx
from fastapi.responses import ORJSONResponse
from fastapi.routing import APIRouter
from fastapi.responses import JSONResponse
from logs.settings import logger
from views.spider_test.func.request import *
from views.spider_test.func.utils import *
from extensions import *

router = APIRouter(
    prefix="/api",
    tags=["测试请求数据"],
    default_response_class=ORJSONResponse
)


@router.post('/spider/data', summary='请求测试', description='', )
async def ApiData(item: dict):
    try:
        task = item.get('task')
        result = MonConn.find_query('data', {"task": task})
        result_list = []
        for item in result:
            _item = {
                '_id': str(item.get('_id')),
                'code': item.get('code'),
                'host': item.get('host'),
                'time': str(item.get('time')),
            }
            result_list.append(_item)
        return result_list
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "detail": str(e)}


@router.post('/spider/data/get', summary='获取任务详情', description='', )
async def ApiGetData(item: dict):
    try:
        item_id = item.get('id')
        result = delid(MonConn.find_id('data', item_id))
        return result
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "detail": str(e)}


@router.post('/spider/curl', summary='请求测试', description='', )
async def ApiCurl(item: dict):
    try:
        data = curl_main(item.get('data'), ck=False, param=False)
        return {
            "url": data.get_url,
            "data": data.get_data,
            "headers": data.get_headers,
            "method": data.get_method,
            "text": data.get_text,
        }
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "detail": str(e)}


@router.post('/curl', summary='请求测试', description='', )
async def ApiCurl(item: dict):
    try:
        data = curl_parse(item.get('data'))
        if data:
            return {
                "data": data,
                "msg": "curl完成"
            }
        else:
            return JSONResponse(status_code=401, content={"msg": "curl失败"})

    except Exception as e:
        logger.error(e)
        return JSONResponse(status_code=401, content={"msg": "curl失败", "detail": str(e)})


@router.post('/spider/add', summary='爬虫测试项目添加', description='', )
async def ApiProAdd(item: dict):
    try:
        name = {"name": item.get('name')}
        if MonConn.find_query('project', name):
            msg = '名称重复'
        else:
            name.update({"date": timenow})
            MonConn.insert('project', name)
            msg = '添加成功'

        return {"status": True, "msg": msg}
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "detail": str(e), "status": False}


@router.get('/spider/project', summary='爬虫测试项目列表', description='', )
async def ApiPro():
    try:
        result = MonConn.findall('project', sortfield="date")
        result_list = []
        for item in result:
            _item = {
                'name': item.get('name'),
                'date': str(item.get('date')),
            }
            result_list.append(_item)
        return {"data": result_list, "msg": "获取项目成功"}
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "detail": str(e)}


@router.post('/spider/task/del', summary='任务删除', description='', )
async def ApiTaskDel(item: dict):
    try:
        task = item.get('task')
        itemName = item.get('itemName')
        if task == "all":
            MonConn.delete_query('data', {"task": itemName})
        else:
            MonConn.delete('data', task)
        result_list = {
            "msg": "success", "status": True
        }

        return result_list
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "status": False, "detail": str(e)}


@router.post('/project/del', summary='任务删除', description='', )
async def ApiProDel(item: dict):
    try:
        datas = item.get('data')
        for i in datas:
            project = i.get('name')
            MonConn.delete_query('project', {"name": project})
        result_list = {
            "msg": "success", "status": True
        }

        return result_list
    except Exception as e:
        logger.error(e)
        return {"msg": "error", "status": False, "detail": str(e)}
